package com.ljm.security.service;

import com.ljm.security.api.SecurityApi;
import com.ljm.security.dto.SecurityUserDetail;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: ChenHuaMing
 * @Date: 2020/6/11 10:09
 * @Description:
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SecurityApi securityApi;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUserDetail userDetail = securityApi.getUser(username);
        if(null==userDetail){
            throw new UsernameNotFoundException("用户不存在");
        }
        //处理权限
        Set<GrantedAuthority> authorities=new HashSet<>();
        if(!CollectionUtils.isEmpty(userDetail.getAuthorities())){
            userDetail.getAuthorities().forEach(auth-> authorities.add(new SimpleGrantedAuthority(auth)));
        }
        return new User(userDetail.getUsername(),userDetail.getPassword(),
                userDetail.isEnabled(),userDetail.isAccountNonExpired(),userDetail.isCredentialsNonExpired(),userDetail.isAccountNonLocked()
                ,authorities);
    }
}
